package com.lm.rdf4j.example;

import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.query.QueryLanguage;
import org.eclipse.rdf4j.query.TupleQuery;
import org.eclipse.rdf4j.query.TupleQueryResult;
import org.eclipse.rdf4j.repository.Repository;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import org.eclipse.rdf4j.repository.sail.SailRepository;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.Rio;
import org.eclipse.rdf4j.sail.memory.MemoryStore;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class FileDataRDF4JExample {
    public static void main(String[] args) throws Exception {
        // 创建内存存储库
        Repository repo = new SailRepository(new MemoryStore());
        repo.init();

        try (RepositoryConnection conn = repo.getConnection()) {
            // 从文件加载 RDF 数据（假设文件位于项目根目录）
            File file = ResourceUtils.getFile("classpath:data.ttl");
//            File file = new File("data.ttl");
            try (InputStream input = new FileInputStream(file)) {
                conn.add(input, "http://example.org/", RDFFormat.TURTLE);
            }

            // SPARQL 查询：查询所有 Person 类型的资源
            String queryString = "PREFIX ex: <http://example.org/> " +
                    "SELECT ?person WHERE { ?person a ex:Person . }";
            TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
            try (TupleQueryResult result = query.evaluate()) {
                while (result.hasNext()) {
                    System.out.println("查询到 Person：" + result.next().getValue("person"));
                }
            }
        }
        repo.shutDown();
    }
}
